#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen
@file: json_tools.back.py
@time: 2023/8/28 9:27
@desc:
"""
# coding:utf-8
import base64
import datetime
import json
import os
import time
import tkinter
from tkinter import ANCHOR, RAISED, END
from tkinter.ttk import *

import requests

from json_tool.baidu_api import get_access_token, api_key, secret_key
from json_tool.icon import Icon
from json_tool.utils import day_laster, get_hot_news, get_today

request_thread = None
import threading


def handle_timestamp_formate(event):
    if time_stamp_input.get():
        need_time = time_stamp_input.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")


def handle_formate_timestamp(event):
    if time_formate_input.get():
        formate_data = time_formate_input.get().strip()
        if len(formate_data) == 10:
            # 转换成时间数组
            time_array = time.strptime(formate_data, "%Y-%m-%d")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                    " + str(time_format), "center")
        elif len(formate_data) == 19:  # "2023-03-21 15:11:25"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M:%S")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                    " + str(time_format), "center")
        elif len(formate_data) == 16:  # "2023-04-01 14:00"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                    " + str(time_format), "center")
    else:
        now_time = int(time.time())
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                    " + str(now_time), "center")  # ADDED


def handle_to_json(event):
    if sting_input.get():
        need_time = sting_input.get().strip()
        sting_output_button.delete('1.0', END)
        try:
            to_json = json.loads(need_time)
            last_send = json.dumps(to_json, ensure_ascii=False, indent=4, separators=(',', ':'))
            sting_output_button.insert(END, last_send, "center")  # ADDED
        except Exception as e:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "字符串格式有误，请确认字符串使用的是为双引号\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


# def handle_chat(event):
#     if ai_input_text_answer.get():
#         chat_message = ai_input_text_answer.get().strip()
#         last_print_text_answer.delete('1.0', END)
#         try:
#             result_message = handle_chat_message(chat_message)
#             last_print_text_answer.insert(END, result_message, "center")  # ADDED
#         except Exception as e:
#             last_print_text_answer.delete('1.0', END)
#             last_print_text_answer.insert(END, "请在左边输入想要咨询的问题\n", "center")  # ADDED
#     else:
#         last_print_text_answer.delete('1.0', END)
#         last_print_text_answer.insert(END, "请在左边输入想要咨询的问题\n", "center")  # ADDED


def handle_chat_message():
    chat_message = sting_input.get().strip()
    if chat_message:
        url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token(
            api_key, secret_key)
        payload = json.dumps({
            "messages": [
                {
                    "role": "user",
                    "content": f"{chat_message}"
                }
            ]
        })
        headers = {
            'Content-Type': 'application/json'
        }
        print(payload, f"start_handle {chat_message}")
        response = requests.request("POST", url, headers=headers, data=payload)
        print(response.text)
        response_message = response.json().get("result")
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, response_message, "center")  # ADDED
        request_thread = None
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请在左边输入想要查询的问题\n", "center")  # ADDED


def start_request_baidu():
    global request_thread
    if request_thread is None or not request_thread.is_alive():
        chat_message = sting_input.get().strip()
        if chat_message:
            download_thread = threading.Thread(target=handle_chat_message)
            download_thread.start()
        else:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "请在左边输入想要查询的问题\n", "center")  # ADDED


def clean_input(event):
    sting_input.delete(0, END)
    # sting_input.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


# def clean_ai_input(event):
#     ai_input_text_answer.delete(0, END)
#     # sting_input.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


def listbox_copy(event):
    window.clipboard_clear()
    selected = last_print_text.get(ANCHOR)
    selected = selected.strip()
    window.clipboard_append(selected)


def copy_to_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(last_print_text.get('1.0', END).rstrip().strip())


def copy_to_json_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(sting_output_button.get('1.0', END).rstrip().strip())


def get_now_time():
    time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')  # 获取当前的时间并转化为字符串
    now_time_label.configure(text=time_str)  # 重新设置标签文本
    window.after(100, get_now_time)  # 每隔1s调用函数 get_now_time 自身获取时间


def handle_week_nums():
    time_str = datetime.datetime.now().weekday()  # 获取当前的时间并转化为字符串
    date_dict = {
        0: "星期一",
        1: "星期二",
        2: "星期三",
        3: "星期四",
        4: "星期五",
        5: "星期六",
        6: "星期日",
    }
    timestr = date_dict.get(time_str)
    dat_num_label.configure(text=timestr)  # 重新设置标签文本
    window.after(1000 * 60, handle_week_nums)  # 每隔1s调用函数 gettime 自身获取时间


def tk_center(window_obj, width, height):
    screen_width = window_obj.winfo_screenwidth()
    screen_height = window_obj.winfo_screenheight()

    x = int(screen_width / 2 - width / 2)
    y = int(screen_height / 2 - height / 2)
    size = '{}x{}+{}+{}'.format(width, height, x, y)
    return size


def local_day_laster():
    send = day_laster()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED
    # tkinter.messagebox.showinfo(title='my message', message=send)


def local_get_today():
    send = get_today()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED
    # tkinter.messagebox.showinfo(title='my message', message=send)


def local_get_hot_news():
    send = get_hot_news()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED
    # tkinter.messagebox.showinfo(title='my message', message=send)


window = tkinter.Tk()

with open('tmp.ico', 'wb') as tmp:
    tmp.write(base64.b64decode(Icon().img))
window.iconbitmap('tmp.ico')
os.remove('tmp.ico')

# window.attributes("-topmost", True)  # 保持当前界面
width = window.winfo_screenwidth()
window.title('小工具 @author  >> henry.oulen@gmail.com')
# the_width = window.winfo_screenwidth()
# the_height = window.winfo_screenheight()
# print(the_height,the_width)
# window.geometry("%dx%d" % (the_width, the_height))
# window.geometry('1920x1080')
# size = tk_center(window, 1920, 1080)
# window.geometry(size)
# the_width, the_height = window.maxsize()
# window.geometry("%dx%d" %(the_width, the_height))


# 获取屏幕尺寸计算参数，使窗口显示再屏幕中央
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
_width = 1920
_height = 1080
# window_size = '%dx%d+%d+%d' % (width, height, (screen_width-width)/2, (screen_height-height)/2)
window_size = f'{_width}x{_height}+{round((screen_width - width) / 2)}+{round((screen_height - _height) / 2)}'  # round去掉小数
# window.geometry(window_size)  # 窗口大小
# window.resizable(width=False,height=False) #设置窗体是否可用改变大小;默认可用改变
# 进入等待与处理窗口（监控每个组件，当组件发生变化或触发事件时，会立即更新窗口）

window.wm_state("zoomed")  # 设置打开的窗口最大化

# 布局

# 周几
dat_num_label = tkinter.Label(window, text='', fg='black', font="等线 20 bold")
dat_num_label.place(relx=0.4, rely=0.02, relwidth=0.1, relheight=0.05)
handle_week_nums()

# 当前时间
now_time_label = tkinter.Label(window, text='', fg='black', font="等线 20 bold")
now_time_label.place(relx=0.5, rely=0.02, relwidth=0.2, relheight=0.05)
get_now_time()

time_stamp_show = Label(window, text='时间戳', font="等线 16 bold")
time_stamp_show.place(relx=0.05, rely=0.1, relwidth=0.1, relheight=0.05)
time_stamp_input = Entry(window, font="等线 16 bold", )
time_stamp_input.place(relx=0.05, rely=0.15, relwidth=0.1, relheight=0.05)

time_formate_show = Label(window, text='时间格式', font="等线 16 bold")
time_formate_show.place(relx=0.15, rely=0.1, relwidth=0.1, relheight=0.05, )
time_formate_input = Entry(window, font="等线 16 bold", justify="center", )
time_formate_input.place(relx=0.15, rely=0.15, relwidth=0.1, relheight=0.05)

timestamp_to_formate = tkinter.Button(window, text="时间戳-->格式化", command="handle_timestamp_formate",
                                      activebackground="#0f73ef",
                                      font="等线 16 bold")
timestamp_to_formate.bind("<Button-1>", handle_timestamp_formate)
timestamp_to_formate.place(relx=0.05, rely=0.2, relwidth=0.1, relheight=0.05)

formate_to_timestamp = tkinter.Button(window, text="时间格式-->时间戳", command="handle_formate_timestamp",
                                      activebackground="#0f73ef",
                                      font="等线 16 bold")
formate_to_timestamp.bind("<Button-1>", handle_formate_timestamp)
formate_to_timestamp.place(relx=0.15, rely=0.2, relwidth=0.1, relheight=0.05)

last_print_text = tkinter.Text(window, width=40, height=10, border=4, relief=RAISED, font="等线 16 bold", )
last_print_text.place(relx=0.05, rely=0.25, relwidth=0.2, relheight=0.1)

clp_text = tkinter.Button(window, text="复制到粘贴板",
                          command=copy_to_clipboard, activebackground="#0f73ef", font="等线 16 bold")
clp_text.place(relx=0.05, rely=0.35, relwidth=0.2, relheight=0.05)

# 定义消息对话框
last_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="节日倒数", command=local_day_laster,
                             font="等线 16 bold")
last_button.pack()
last_button.place(relx=0.05, rely=0.42, relwidth=0.05, relheight=0.05)

get_hot_news_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="今日热榜",
                                     command=local_get_hot_news,
                                     font="等线 16 bold")
get_hot_news_button.pack()
get_hot_news_button.place(relx=0.125, rely=0.42, relwidth=0.05, relheight=0.05)

get_today_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="历史今天", command=local_get_today,
                                  font="等线 16 bold")
get_today_button.pack()
get_today_button.place(relx=0.2, rely=0.42, relwidth=0.05, relheight=0.05)

# 讯飞 api对话
# ai_input_text_answer = Entry(window, font="等线 16 bold", )
# ai_input_text_answer.place(relx=0.05, rely=0.45, relwidth=0.2, relheight=0.1)
#
# sed_text = tkinter.Button(window, text="发送数据",activebackground="#0f73ef", font="等线 16 bold")
# sed_text.bind("<Button-1>", handle_chat)
# sed_text.place(relx=0.05, rely=0.55, relwidth=0.1, relheight=0.05)
#
# clean_text = tkinter.Button(window, text="清空内容",activebackground="#0f73ef", font="等线 16 bold")
# clean_text.bind("<Button-1>", clean_ai_input)
# clean_text.place(relx=0.15, rely=0.55, relwidth=0.1, relheight=0.05)
#
last_print_text_answer = tkinter.Text(window, width=40, height=10, border=4, relief=RAISED, font="等线 13 bold", )
last_print_text_answer.place(relx=0.05, rely=0.50, relwidth=0.2, relheight=0.45)

# python日志使用
# 右边
sting_input = tkinter.Entry(window, font="等线 16 bold", )
sting_input.place(relx=0.3, rely=0.1, relwidth=0.28, relheight=0.05)

sting_input_button = tkinter.Button(window, text="Json格式化", command="handle_formate_timestamp",
                                    activebackground="#0f73ef",
                                    font="等线 16 bold")
sting_input_button.bind("<Button-1>", handle_to_json)
sting_input_button.place(relx=0.55, rely=0.1, relwidth=0.1, relheight=0.05)

baidu_btn_button = tkinter.Button(window, text="文心一言", command=start_request_baidu,
                                  activebackground="#0f73ef",
                                  font="等线 16 bold")
# baidu_btn_button.bind("<Button-1>", handle_chat_baidu)
baidu_btn_button.place(relx=0.65, rely=0.1, relwidth=0.1, relheight=0.05)

sting_clean_button = tkinter.Button(window, text="清空内容", command="handle_formate_timestamp",
                                    activebackground="#0f73ef",
                                    font="等线 16 bold")
sting_clean_button.bind("<Button-1>", clean_input)
sting_clean_button.place(relx=0.75, rely=0.1, relwidth=0.1, relheight=0.05)

clp_json = tkinter.Button(window, text="复制到粘贴板",
                          command=copy_to_json_clipboard, activebackground="#0f73ef", font="等线 16 bold")
clp_json.place(relx=0.85, rely=0.1, relwidth=0.1, relheight=0.05)

sting_output_button = tkinter.Text(window, width=40, height=10, border=4, relief=RAISED, font="等线 16 bold", )
sting_output_button.place(relx=0.3, rely=0.15, relwidth=0.65, relheight=0.8)

window.mainloop()
